package com.lesales.controller;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.lesales.common.exception.EntityOperateException;
import com.lesales.common.exception.ValidatException;
import com.lesales.model.Function;
import com.lesales.model.RoleFunction;
import com.lesales.model.User;
import com.lesales.model.UserRole;
import com.lesales.service.interfaces.IAccountService;
import com.lesales.service.interfaces.IFunctionService;
import com.lesales.service.interfaces.IRoleFunctionService;
import com.lesales.service.interfaces.IUserRoleService;

@Controller
@RequestMapping(value = "/account")
public class AccountController extends BaseController {

	@Autowired
	@Qualifier("accountServiceImpl")
	private IAccountService accountService;

	@Autowired
	@Qualifier("userRoleServiceImpl")
	private IUserRoleService userRoleService;

	@Autowired
	@Qualifier("roleFunctionServiceImpl")
	private IRoleFunctionService roleFunctionService;

	@Autowired
	@Qualifier("functionServiceImpl")
	private IFunctionService functionService;
	private User lookUpUser1;
	private Integer userId = 1;

	@RequestMapping(value = "/login", method = { RequestMethod.GET })
	public String login(Model model) {

		if (!model.containsAttribute("user")) {
			model.addAttribute("user", new User());
		}
		return "account/login";
	}

	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public String login(Model model, @Valid User user, BindingResult result, HttpServletRequest request)
			throws ValidatException, EntityOperateException, NoSuchAlgorithmException {
		if (result.hasErrors()) {
			return login(model);
		}
		List<User> users1 = accountService.checkName(user);
		if (users1.isEmpty()) {
			result.addError(new FieldError("user", "userName", "用户名不存在"));
			return login(model);
		} else {
			User user1 = users1.get(0);
			if (!user1.getPassword().equals(user.getPassword())) {
				result.addError(new FieldError("user", "password", "密码错误"));
				return login(model);
			} else {
				userId = user1.getId();
				List<UserRole> userRoles = new ArrayList<>();
				List<RoleFunction> roleFunctions = new ArrayList<>();
				Set<Function> functions = new HashSet<Function>();
				userRoles = userRoleService.findRoleIdByUserId(userId);
				for (UserRole userRole : userRoles) {
					int role_id = userRole.getRoleId();
					roleFunctions = roleFunctionService.findFunctionByRoleId(role_id);
					for (RoleFunction roleFunction : roleFunctions) {
						int function_id = roleFunction.getFunctionId();
						Function function_get = functionService.findFunctionById(function_id).get(0);
						functions.add(function_get);
					}
				}
				request.getSession().setAttribute("user1", user1);
				model.addAttribute("functions", functions);
				return "home/home";
			}
		}
	}

	@RequestMapping(value = "/register", method = { RequestMethod.GET })
	public String register(Model model) {
		if (!model.containsAttribute("registerUser")) {
			model.addAttribute("registerUser", new User());
		}
		return "account/register";
	}

	@RequestMapping(value = "/register", method = { RequestMethod.POST })
	public String register(Model model, @Valid User registerUser,
			@RequestParam("confirmPassword") String confirmPassword, BindingResult result)
			throws EntityOperateException, ValidatException, NoSuchAlgorithmException {
		if (result.hasErrors()) {
			return register(model);
		}
		List<User> users = null;
		users = accountService.checkName(registerUser);
		if (users.isEmpty()) {
			if (!registerUser.getPassword().equals(confirmPassword)) {
				return "account/register";
			} else {
				model.addAttribute("registerUser", registerUser);
				accountService.saveRegister(registerUser);
				return "redirect:manageUser";
			}
		} else {
			return "redirect:account/register";
		}

	}

	@RequestMapping(value = "/manageUser", method = { RequestMethod.GET })
	public String lookUpUser(Model model) {
		if (!model.containsAttribute("lookUpUser")) {
			model.addAttribute("lookUpUser", new User());
		}
		return "account/manageUser";
	}

	@RequestMapping(value = "/manageUser", method = { RequestMethod.POST })
	public String lookUpUser(HttpServletRequest request, Model model, @Valid User lookUpUser, BindingResult result)
			throws ValidatException, EntityOperateException, NoSuchAlgorithmException {
		List<User> users = accountService.checkName(lookUpUser);
		if (users.isEmpty()) {
			result.addError(new FieldError("lookUpUser", "userName", "用户名不存在"));
			return lookUpUser(model);
		} else {
			lookUpUser1 = users.get(0);
			model.addAttribute("lookUpUser", lookUpUser1);
			request.getSession().setAttribute("lookUpUser", lookUpUser1);
			return "account/manageUser";
		}
	}

	@RequestMapping(value = "/deleteUser", method = { RequestMethod.GET })
	public String deleteUser(Model model) {
		return "account/deleteUser";
	}

	@RequestMapping(value = "/deleteUser", method = { RequestMethod.POST })
	public String deleteUser(Model model, User user) {
		List<User> users = accountService.checkName(user);
		lookUpUser1 = users.get(0);
		accountService.delete(lookUpUser1);
		return "redirect:manageUser";
	}

	@RequestMapping(value = "/updateUser", method = { RequestMethod.GET })
	public String updateUser(Model model) {
		if (!model.containsAttribute("updateUser")) {
			model.addAttribute("updateUser", new User());
		}
		return "account/updateUser";
	}

	@RequestMapping(value = "/updateUser", method = { RequestMethod.POST })
	public String updateUser(Model model, User updateUser) {
		List<User> users = accountService.checkName(updateUser);
		lookUpUser1 = users.get(0);
		lookUpUser1.setUserName(updateUser.getUserName());
		lookUpUser1.setUserPhone(updateUser.getUserPhone());
		lookUpUser1.setEmployeeId(updateUser.getEmployeeId());
		lookUpUser1.setPassword(updateUser.getPassword());
		accountService.update(lookUpUser1);
		return "redirect:manageUser";
	}
}
